package com.satoken.util;

import cn.dev33.satoken.SaManager;
import cn.dev33.satoken.config.SaTokenConfig;
import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.context.model.SaRequest;
import cn.dev33.satoken.oauth2.logic.SaOAuth2Util;
import cn.dev33.satoken.oauth2.model.AccessTokenModel;
import cn.dev33.satoken.oauth2.model.RequestAuthModel;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaFoxUtil;
import cn.dev33.satoken.util.SaTokenConsts;
import com.satoken.config.SaOauth2AppInfo;
import com.satoken.exception.TokenException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

@Component
public class SaOath2UtilImpl  extends SaOAuth2Util {
    private static final String ACCESS_TOKEN_KEY_PREFIX = "access_token_";
    private static final String REFRESH_TOKEN_KEY_PREFIX = "refresh_token_";
    @Autowired
    SaOauth2AppInfo saOauth2AppInfo;

    @Autowired
    RedisOperator redisOperator;

    /**
     * @throws UnsupportedEncodingException
     */
    public Map<String, Object> createAccessTokenAndRefreshToken() throws UnsupportedEncodingException {
        RequestAuthModel authModel = new RequestAuthModel()
                .setClientId(saOauth2AppInfo.getClientId())			// 应用id
                .setScope(saOauth2AppInfo.getScope())				// 授权类型
                .setLoginId(StpUtil.getLoginIdAsLong())					// 当前登录账号id
                .setRedirectUri(URLDecoder.decode(saOauth2AppInfo.getRedirectUri(), "utf-8"))	// 重定向地址
                .checkModel();
//            SaOAuth2Util.generateClientToken(saOauth2AppInfo.getClientId(),saOauth2AppInfo.getScope());
        AccessTokenModel accessTokenModel = SaOAuth2Util.generateAccessToken(authModel, true);
        Map<String, Object> lineMap = accessTokenModel.toLineMap();
        String accessTokenKey = ACCESS_TOKEN_KEY_PREFIX + lineMap.get("access_token");
        String refreshTokenKey = REFRESH_TOKEN_KEY_PREFIX + lineMap.get("refresh_token") +lineMap.get("access_token");
        redisOperator.set(accessTokenKey,(String) lineMap.get("access_token"),saOauth2AppInfo.getAccessTokenTimeout());
        redisOperator.set(refreshTokenKey,(String) lineMap.get("refresh_token"),saOauth2AppInfo.getRefreshTokenTimeout());
        return lineMap;
    }

    /**
     * 检查access_token 是否有效
     * @param accessToken
     */
    public void checkTokenValid(String accessToken){
        String accessTokenKey = ACCESS_TOKEN_KEY_PREFIX + accessToken;
        String accessTokenRedis = redisOperator.get(accessTokenKey);
        if (StringUtils.isEmpty(accessTokenRedis)){
            throw new TokenException(TokenException.ACCESS_TOKEN_TIMEOUT);
        }
    }

    /**
     * 检查refresh_token是否有效
     * @param accessToken
     * @param reFreshToken
     */
    public void checkRefreshTokenValid(String accessToken,String reFreshToken){
        String refreshTokenKey = REFRESH_TOKEN_KEY_PREFIX + reFreshToken + accessToken;
        String refreshTokenRedis = redisOperator.get(refreshTokenKey);
        if (StringUtils.isEmpty(refreshTokenKey)){
            throw new TokenException(TokenException.REFRESH_TOKEN_TIMEOUT);
        }

    }

    public  void checkAccessToken(){
        String tokenCute = getAccessTokenCute();
        checkTokenValid(tokenCute);
    }


    public String getAccessTokenCute(){
        SaRequest request = SaHolder.getRequest();
        SaTokenConfig config = SaManager.getConfig();
        String authorization = request.getHeader("Authorization");
        // 2. 如果打开了前缀模式，则裁剪掉
        String tokenPrefix = config.getTokenPrefix();
        if(SaFoxUtil.isEmpty(tokenPrefix) == false) {
            // 如果token并没有按照指定的前缀开头，则视为未提供token
            if (SaFoxUtil.isEmpty(authorization)){
                return  null;
            }
            if(authorization.startsWith(tokenPrefix + SaTokenConsts.TOKEN_CONNECTOR_CHAT) == false) {
                return authorization;
            } else {
                // 则裁剪掉前缀
                return authorization.substring(tokenPrefix.length() + SaTokenConsts.TOKEN_CONNECTOR_CHAT.length());
            }
        }
        return null;
    }
}
